import React, { useState, useEffect, useImperativeHandle } from 'react';
import { Input, Form, Select, Button, Badge, Drawer, Tooltip, message } from 'antd';
import IconFont from '@/components/IconFont';
import GradeSelector from '@/pages/Organization/Job/components/GradeSelector';
import { size } from 'lodash';
import moment from 'moment';
import OrganizationSelect from '@/components/OrganizationSelect';
import DutySelect from '@/components/DutySelect';
import { eventTrack } from '@/utils/track';
import RadioButton from './components/RadioButton';
import styles from './index.less';
import QuickRangeDate from './components/QuickRangeDate';
import { getDegreeList, getWorkAgeList, getAgeList, getSexList } from '../../services';
import { formatRange, generationRange } from './utils';
import PositionSelect from '../PositionSelect';

const { Option } = Select;
const FilterKeysArray = [
    'highestDegreeList',
    'rankCodeList',
    'workAgeRange',
    'entryDate',
    'ageRange',
    'sex',
    'dutyCodes',
    'positionCodes'
];

// 纪念日map
const CARE_EVENT_ARRAY = [
    { label: '生日员工', value: 1 },
    { label: '入职周年', value: 2 }
];

// 员工管理列表搜索
const EmployeeListSearch = React.forwardRef(({ form, onSearch, data }, ref) => {
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [degreeList, setDegreeList] = useState([]);
    const [workAgeList, setWorkAgeList] = useState([]);
    const [ageList, setAgeList] = useState([]);
    const [sexList, setSexList] = useState([]);
    const [filterCounts, setFilterCounts] = useState(0);
    const { getFieldDecorator, setFieldsValue } = form;

    // 获取筛选列表数据
    useEffect(() => {
        const getInit = async () => {
            const degreeListResult = await getDegreeList();
            const workAgeListResult = await getWorkAgeList();
            const ageListResult = await getAgeList();
            const sexListResult = await getSexList();
            setDegreeList(degreeListResult);
            setWorkAgeList(workAgeListResult);
            setAgeList(ageListResult);
            setSexList(sexListResult);
        };
        getInit();
    }, []);

    // 搜索
    const handleSearchSubmit = async () => {
        if (onSearch) {
            const {
                keyword,
                organizationCodes,
                administrativeOrganizationCodes,
                careEvent,
                careEventValue,
                highestDegreeList,
                rankCodeList,
                workAgeRange,
                entryDate,
                ageRange,
                sex,
                dutyCodes,
                positionCodes
            } = form.getFieldsValue();

            await eventTrack({
                eventName: 'personnel_management_organization_employee_list_search_submit_click',
                pageName: 'personnel_management_organization',
                eventProps: {
                    click_context: `关键词:${keyword ||
                        '空'},组织机构:${organizationCodes},行政机构：${administrativeOrganizationCodes},纪念日：${
                        careEvent ? CARE_EVENT_ARRAY[careEvent - 1].label : null
                    },${careEventValue || 0}月`
                }
            });

            const searchObj = {
                ageStart: undefined,
                ageEnd: undefined,
                seniorityStart: undefined,
                seniorityEnd: undefined,
                entryDateStart: undefined,
                entryDateEnd: undefined
            };

            try {
                if (ageRange) {
                    const [ageStart, ageEnd] = await formatRange(ageRange);
                    searchObj.ageStart = ageStart;
                    searchObj.ageEnd = ageEnd;
                }

                if (workAgeRange) {
                    const [seniorityStart, seniorityEnd] = await formatRange(workAgeRange);
                    searchObj.seniorityStart = seniorityStart;
                    searchObj.seniorityEnd = seniorityEnd;
                }

                if (entryDate?.length) {
                    searchObj.entryDateStart = entryDate[0].format('YYYY-MM-DD');
                    searchObj.entryDateEnd = entryDate[1].format('YYYY-MM-DD');
                }

                const result = Object.assign(
                    {
                        keyword,
                        organizationCodes,
                        administrativeOrganizationCodes,
                        dutyCodes,
                        positionCodes,
                        careEvent,
                        careEventValue,
                        highestDegreeList,
                        rankCodeList,
                        sex
                    },
                    searchObj
                );
                console.log('getFormValue :>> ', result);
                onSearch(result);
            } catch (error) {
                message.error(error.message);
            }
        }
    };

    const closeDrawer = () => {
        setDrawerVisible(false);
    };

    const computeFilterCount = () => {
        const values = form.getFieldsValue();
        let count = 0;
        FilterKeysArray.forEach(item => {
            if (item !== 'workAgeRange' && item !== 'ageRange') {
                if (size(values[item])) {
                    count += 1;
                }
            }
            if (item === 'workAgeRange' && values[item] !== undefined && values[item] !== '[-]') {
                count += 1;
            }

            if (item === 'ageRange' && values[item] !== undefined && values[item] !== '[-]') {
                count += 1;
            }
        });
        setFilterCounts(count);
    };

    const handleDrawerSubmit = async () => {
        computeFilterCount();
        closeDrawer();
        await handleSearchSubmit();
    };

    // 初始化数据
    useEffect(() => {
        const setInitFormValue = async () => {
            const {
                keyword,
                organizationCodes,
                administrativeOrganizationCodes,
                careEvent,
                careEventValue,
                highestDegreeList,
                rankCodeList,
                sex,
                ageStart,
                ageEnd,
                seniorityStart,
                seniorityEnd,
                entryDateStart,
                entryDateEnd,
                dutyCodes,
                positionCodes
            } = data || {};

            let ageRange;
            let workAgeRange;
            let entryDate;

            if (ageStart !== undefined && ageEnd !== undefined) {
                try {
                    ageRange = await generationRange(ageStart, ageEnd);
                } catch (error) {
                    message.error(error.message);
                }
            }

            if (seniorityStart !== undefined && seniorityEnd !== undefined) {
                try {
                    workAgeRange = await generationRange(seniorityStart, seniorityEnd);
                } catch (error) {
                    message.error(error.message);
                }
            }

            if (entryDateStart !== undefined && entryDateEnd !== undefined) {
                try {
                    entryDate = [moment(entryDateStart), moment(entryDateEnd)];
                } catch (error) {
                    message.error(error.message);
                }
            }

            const result = Object.assign(
                {
                    keyword,
                    organizationCodes,
                    administrativeOrganizationCodes,
                    careEvent,
                    careEventValue,
                    highestDegreeList,
                    rankCodeList,
                    sex,
                    dutyCodes,
                    positionCodes
                },
                {
                    ageRange,
                    workAgeRange,
                    entryDate
                }
            );
            // console.log('setFormValue :>> ', result);
            setFieldsValue(result);

            let count = 0;
            FilterKeysArray.forEach(item => {
                if (item !== 'workAgeRange' && item !== 'ageRange') {
                    if (size(result[item])) {
                        count += 1;
                    }
                }
                if (item === 'workAgeRange' && result[item] !== undefined && result[item] !== '[-]') {
                    count += 1;
                }

                if (item === 'ageRange' && result[item] !== undefined && result[item] !== '[-]') {
                    count += 1;
                }
            });
            setFilterCounts(count);
        };

        setInitFormValue();
    }, [data, setFieldsValue]);

    useImperativeHandle(ref, () => ({
        form
    }));

    const handleCleanForm = () => {
        const obj = {};
        FilterKeysArray.forEach(item => {
            obj[item] = undefined;
        });
        setFieldsValue(obj);
    };

    return (
        <div>
            <Form layout="inline">
                <Form.Item
                    label={
                        <span>
                            关键字
                            <Tooltip
                                placement="top"
                                getPopupContainer={() => document.body}
                                arrowPointAtCenter
                                title="支持按照员工姓名、用户名、工号、手机号、个人邮箱、企业邮箱进行模糊匹配查询"
                            >
                                <IconFont icon="info-circle" style={{ fontSize: 12, marginLeft: 5 }} />
                            </Tooltip>
                        </span>
                    }
                >
                    {getFieldDecorator('keyword')(
                        <Input
                            placeholder="请输入关键字"
                            allowClear
                            onFocus={() => {
                                eventTrack({
                                    eventName: 'personnel_management_organization_employee_list_keyword_input_click',
                                    pageName: 'personnel_management_organization'
                                });
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="组织机构">
                    {getFieldDecorator('organizationCodes')(
                        <OrganizationSelect
                            treeCheckable
                            isFunctional
                            isStrictly
                            strictlyOutType="string"
                            maxTagCount={2}
                            isNeedPermission
                            style={{ width: 250 }}
                            onFocus={() => {
                                eventTrack({
                                    eventName: 'personnel_management_organization_employee_list_zzjg_input_click',
                                    pageName: 'personnel_management_organization'
                                });
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="行政机构">
                    {getFieldDecorator('administrativeOrganizationCodes')(
                        <OrganizationSelect
                            treeCheckable
                            isStrictly
                            maxTagCount={2}
                            style={{ width: 250 }}
                            isNeedPermission
                            onFocus={() => {
                                eventTrack({
                                    eventName: 'personnel_management_organization_employee_list_xzjg_input_click',
                                    pageName: 'personnel_management_organization'
                                });
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="纪念日">
                    <Input.Group compact>
                        <Form.Item style={{ marginRight: '10px' }}>
                            {getFieldDecorator('careEvent')(
                                <Select
                                    placeholder="请选择"
                                    style={{ minWidth: 120 }}
                                    allowClear
                                    onFocus={() => {
                                        eventTrack({
                                            eventName:
                                                'personnel_management_organization_employee_list_jnr_input_click',
                                            pageName: 'personnel_management_organization'
                                        });
                                    }}
                                >
                                    {CARE_EVENT_ARRAY.map(item => (
                                        <Option key={item.value} vlaue={item.value}>
                                            {item.label}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item>
                            {getFieldDecorator('careEventValue')(
                                <Select
                                    placeholder="请选择"
                                    style={{ minWidth: 120 }}
                                    allowClear
                                    onFocus={() => {
                                        eventTrack({
                                            eventName:
                                                'personnel_management_organization_employee_list_jnr_input_click',
                                            pageName: 'personnel_management_organization'
                                        });
                                    }}
                                >
                                    {Array.from(Array(12), (e, i) => {
                                        const num = i + 1;
                                        return (
                                            <Option key={num} vlaue={num}>
                                                {num}月
                                            </Option>
                                        );
                                    })}
                                </Select>
                            )}
                        </Form.Item>
                    </Input.Group>
                </Form.Item>
                <Form.Item>
                    <Badge count={filterCounts}>
                        <Button
                            type="ghost"
                            style={{ padding: '0 10px' }}
                            onClick={async () => {
                                setDrawerVisible(true);
                                await eventTrack({
                                    eventName: 'personnel_management_organization_employee_list_screen_submit_click',
                                    pageName: 'personnel_management_organization'
                                });
                            }}
                        >
                            <IconFont
                                icon="iconsearchbar_filter_icon_default"
                                style={{ fontSize: 20, verticalAlign: 'middle', marginRight: 5 }}
                            />
                            筛选
                        </Button>
                    </Badge>
                </Form.Item>
                <Form.Item>
                    <Button type="primary" onClick={handleSearchSubmit}>
                        搜索
                    </Button>
                </Form.Item>
            </Form>

            <Drawer
                title="筛选"
                width={480}
                onClose={() => {
                    setDrawerVisible(false);
                }}
                visible={drawerVisible}
                bodyStyle={{ paddingTop: 16, paddingBottom: 53 }}
            >
                <div className={styles.filterItemWrapper}>
                    <p className={styles.filterItemTitle}>最高学历</p>
                    <Form.Item>
                        {getFieldDecorator('highestDegreeList')(
                            <Select allowClear mode="multiple" style={{ width: '100%' }} placeholder="请选择学历">
                                {degreeList.map(item => (
                                    <Option key={item.value} vlaue={item.value}>
                                        {item.label}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                </div>
                <div className={styles.filterItemWrapper}>
                    <p className={styles.filterItemTitle}>职级范围</p>
                    <Form.Item>
                        {getFieldDecorator('rankCodeList')(
                            <GradeSelector
                                style={{ display: 'block' }}
                                placeholder="请选择职级范围"
                                allowClear
                                mode="multiple"
                            />
                        )}
                    </Form.Item>
                </div>
                <div className={styles.filterItemWrapper}>
                    <p className={styles.filterItemTitle}>岗位</p>
                    <Form.Item>
                        {getFieldDecorator('dutyCodes')(
                            <DutySelect mode="multiple" placeholder="请选择岗位" style={{ width: '100%' }} />
                        )}
                    </Form.Item>
                </div>
                <div className={styles.filterItemWrapper}>
                    <p className={styles.filterItemTitle}>职位</p>
                    <Form.Item>
                        {getFieldDecorator('positionCodes')(
                            <PositionSelect mode="multiple" style={{ width: '100%' }} />
                        )}
                    </Form.Item>
                </div>
                <div className={styles.filterItemWrapper}>
                    <p className={styles.filterItemTitle}>工龄范围</p>
                    <Form.Item>
                        {getFieldDecorator('workAgeRange')(<RadioButton col={3} list={workAgeList} />)}
                    </Form.Item>
                </div>
                <div className={styles.filterItemWrapper}>
                    <p className={styles.filterItemTitle}>入职日期</p>
                    <Form.Item>{getFieldDecorator('entryDate')(<QuickRangeDate />)}</Form.Item>
                </div>
                <div className={styles.filterItemWrapper}>
                    <p className={styles.filterItemTitle}>年龄范围</p>
                    <Form.Item>{getFieldDecorator('ageRange')(<RadioButton col={3} list={ageList} />)}</Form.Item>
                </div>
                <div className={styles.filterItemWrapper}>
                    <p className={styles.filterItemTitle}>性别</p>
                    <Form.Item>{getFieldDecorator('sex')(<RadioButton col={3} list={sexList} />)}</Form.Item>
                </div>
                <div
                    style={{
                        position: 'absolute',
                        zIndex: 10,
                        right: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right'
                    }}
                >
                    <Button onClick={async () => handleCleanForm()} style={{ marginRight: 8 }}>
                        重置
                    </Button>
                    <Button onClick={() => handleDrawerSubmit()} type="primary">
                        确定
                    </Button>
                </div>
            </Drawer>
        </div>
    );
});

export default Form.create()(EmployeeListSearch);
